import request from '@/utils/request'
import type {
  ChatRequest,
  ApiKeyConfig,
  ApiKeyResponse,
  TestApiKeyResponse,
  ChatSession,
  ChatSessionDetail,
  CreateSessionRequest,
  UpdateSessionTitleRequest,
  SaveMessageRequest,
  ChatMessageDTO,
  ImageGenerationConfig,
  ExtendedChatRequest
} from '@/types/aiChat'

// 获取JWT Token
const getToken = () => {
  return localStorage.getItem('token') || ''
}

/**
 * 发送流式消息
 * @param data 聊天请求数据
 * @param onChunk 处理流式数据的回调函数
 * @param onError 错误处理回调
 * @returns Promise
 */
export const sendMessageStream = (
  data: ChatRequest,
  onChunk: (chunk: string) => void,
  onError?: (error: Error) => void
): Promise<void> => {
  return new Promise((resolve, reject) => {
    const token = getToken()

    // 简化的错误处理
    let isCompleted = false

    const handleError = (error: Error) => {
      if (isCompleted) return
      isCompleted = true
      if (onError) {
        onError(error)
      } else {
        reject(error)
      }
    }

    const handleComplete = () => {
      if (isCompleted) return
      isCompleted = true
      resolve()
    }

    // 使用fetch API发送POST请求并处理SSE响应
    fetch('/api/ai-chat/send', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
        'Accept': 'text/event-stream',
        'Cache-Control': 'no-cache'
      },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (isCompleted) return // 已经超时或完成

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder()

      const readStream = () => {
        if (isCompleted) return

        reader.read().then(({ done, value }) => {
          if (isCompleted) return

          if (done) {
            handleComplete()
            return
          }

          const chunk = decoder.decode(value, { stream: true })
          const lines = chunk.split('\n')

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6).trim()
              
              if (data === '[DONE]') {
                handleComplete()
                return
              }
              
              if (data) {
                try {
                  // 检查是否是JSON格式的数据
                  if (data.startsWith('{')) {
                    const jsonData = JSON.parse(data)

                    // 检查是否是错误消息
                    if (jsonData.error) {
                      handleError(new Error(jsonData.error))
                      return
                    }

                    // 检查是否是推理内容或回答内容
                    if (jsonData.type && jsonData.content) {
                      onChunk(jsonData) // 传递完整的JSON对象
                    } else {
                      // 其他JSON数据，转为字符串
                      onChunk(JSON.stringify(jsonData))
                    }
                  } else {
                    // 纯文本内容（向后兼容）
                    const textContent = typeof data === 'string' ? data : String(data)
                    onChunk(textContent)
                  }
                } catch (e) {
                  // 如果不是JSON，直接作为文本处理
                  const textContent = typeof data === 'string' ? data : String(data)
                  onChunk(textContent)
                }
              }
            }
          }

          // 异步化递归调用，避免阻塞主线程
          setTimeout(() => readStream(), 0)
        }).catch(error => {
          if (!isCompleted) {
            handleError(error)
          }
        })
      }

      readStream()
    })
    .catch(error => {
      if (!isCompleted) {
        handleError(error)
      }
    })
  })
}

/**
 * 保存API Key配置
 * @param data API Key配置数据
 * @returns Promise
 */
export const saveApiKey = (data: ApiKeyConfig) => {
  return request.post('/ai-chat/api-key', data)
}

/**
 * 获取API Key配置
 * @returns Promise<ApiKeyResponse>
 */
export const getApiKey = (): Promise<ApiKeyResponse> => {
  return request.get('/ai-chat/api-key')
}

/**
 * 测试API Key是否有效
 * @returns Promise<TestApiKeyResponse>
 */
export const testApiKey = (): Promise<TestApiKeyResponse> => {
  return request.post('/ai-chat/api-key/test')
}

// ========== 会话管理相关接口 ==========

/**
 * 创建新会话
 */
export const createSession = (data: CreateSessionRequest) => {
  return request.post<ChatSession>('/chat/sessions', data)
}

/**
 * 获取用户的会话列表
 */
export const getSessions = (page = 0, size = 20) => {
  return request.get<ChatSession[]>('/chat/sessions', {
    params: { page, size }
  })
}

/**
 * 获取会话详情（包含消息）
 */
export const getSessionDetail = (sessionId: number) => {
  return request.get<ChatSessionDetail>(`/chat/sessions/${sessionId}`)
}

/**
 * 更新会话标题
 */
export const updateSessionTitle = (sessionId: number, data: UpdateSessionTitleRequest) => {
  return request.put<void>(`/chat/sessions/${sessionId}/title`, data)
}

/**
 * 删除会话
 */
export const deleteSession = (sessionId: number) => {
  return request.delete<void>(`/chat/sessions/${sessionId}`)
}

/**
 * 保存消息到会话
 */
export const saveMessage = (sessionId: number, data: SaveMessageRequest) => {
  return request.post<ChatMessageDTO>(`/chat/sessions/${sessionId}/messages`, data)
}

/**
 * 清空会话的所有消息
 */
export const clearSessionMessages = (sessionId: number) => {
  return request.delete<void>(`/chat/sessions/${sessionId}/messages`)
}
